﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.GHRMS.BLL;
using _WebShared.Classes;
using Telerik.Web.UI;
using KPIS.DBM;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class Mail_BgmProjectOperation : System.Web.UI.UserControl
    {
        Main main = new Main();
        BGM_ProjectReport.BGM_ProjectReport pjreport = new BGM_ProjectReport.BGM_ProjectReport();
        BGM_ProjectOperation.BGM_ProjectOperation oper = new BGM_ProjectOperation.BGM_ProjectOperation();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense poexp = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        BGM_ProjectOperationPerson.BGM_ProjectOperationPerson poper = new BGM_ProjectOperationPerson.BGM_ProjectOperationPerson();
        BGM_ProjectOperationReport.BGM_ProjectOperationReport poreport = new BGM_ProjectOperationReport.BGM_ProjectOperationReport();
        BGM_Project.BGM_Project proj = new BGM_Project.BGM_Project();
        BGM_MAS_Option.BGM_MAS_Option op = new BGM_MAS_Option.BGM_MAS_Option();
        B_HrmEmployees emplist = new B_HrmEmployees();
        B_MessageSend send = new B_MessageSend();
        B_MessageReply reply = new B_MessageReply();
        B_SECURITY_Users user = new B_SECURITY_Users();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        public void LoadData(string strBgmProjOperSeq, string strSender
            , string strApprovePathSeq, string strSendSeq, string strStatus, bool bEdit)
        {

            lblSendSeq.Text = strSendSeq;
            lblApprovePathSeq.Text = strApprovePathSeq;
            BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = oper.GetInfo(strBgmProjOperSeq);
            BGM_Project.M_BGM_Project projInfo = proj.GetInfo(operInfo.bgm_proj_seq.ToString());

            lblBgmProjOperSeq.Text = strBgmProjOperSeq;
            lblFinBgmSubActName.Text = main.FinString(projInfo.m_bgm_subactivity.bgm_strat_list_name);
            lblFinBgmActName.Text = main.FinString(projInfo.m_bgm_activity.bgm_strat_list_name);
            lblFinBgmOutputName.Text = main.FinString(projInfo.m_bgm_output.bgm_strat_list_name);
            lblFinBgmProjName.Text = main.FinString(projInfo.bgm_proj_name);

            lblFinAttendCount.Text = main.FinString(operInfo.attend_count.ToString());
            lblFinBgmProjOperDate.Text = main.FinString(operInfo.bgm_proj_oper_date.Value.ToShortDateString());
            lblFinBgmProjOperName.Text = main.FinString(operInfo.bgm_proj_oper_name);
            lblFinBgmYear.Text = main.FinString(operInfo.bgm_year.ToString());
            lblFinEndDate.Text = main.ConvertDBDateTimeToString(operInfo.end_date, false);
            lblFinStartDate.Text = main.ConvertDBDateTimeToString(operInfo.start_date, false);

            LoadSenderInfo(operInfo.emp_seq.ToString());
            LoadFinProjectExpense(strBgmProjOperSeq, operInfo.bgm_proj_seq.ToString());

            IList<BGM_MAS_Option.M_BGM_MAS_Option> optionInfoList = op.GetListFromBgmProjSeq("3", operInfo.bgm_proj_seq.ToString());// HardCode
            Repeater2.DataSource = optionInfoList;
            Repeater2.DataBind();

            IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> personInfoList = poper.GetFull(strBgmProjOperSeq);
            Repeater3.DataSource = personInfoList;
            Repeater3.DataBind();

            bool bEnable = strStatus == "2";
            cmdApprove.Enabled = !bEnable && bEdit;
            cmdForword.Enabled = !bEnable && bEdit;
            cmdSendBack.Enabled = !bEnable && bEdit;
            PanelOption.Visible = true;
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            PanelSend.Visible = false;
            txtRemark.Text = "";
            LoadApprover();
        }

        protected void LoadApprover()
        {
            int nStepNo = 1;
            string strNextStepNo = send.GetNextStepNo(lblApprovePathSeq.Text, lblFinSumAmount.Text);

            if (Int32.TryParse(strNextStepNo, out nStepNo))
            {
                if (nStepNo > 0)
                {
                    cmdApprove.Visible = false;
                    cmdForword.Visible = true;

                    // Edit by Aek 2014-07-29
                    // Calculate base on to_emp_seq field in table message_send, not login session 
                    DataTable dtb = send.GetCurrentApprover(null, lblSendSeq.Text, "BGM_PROJECT_OPERATION", nStepNo);

                    if (dtb != null)
                    {
                        if (dtb.Rows.Count > 0)
                        {
                            lblNewApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                            //ddlApprover.SelectedValue = dtb.Rows[0]["emp_seq"].ToString();
                            LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
                        }
                    }
                }
                else
                {
                    cmdApprove.Visible = true;
                    cmdForword.Visible = false;
                }
            }
        }

        //protected void SetApproverRight()
        //{
        //    cmdApprove.Visible = user.CheckIsApprover(Session["EmpSeq"].ToString());
        //}

        protected void LoadSenderInfo(string strEmpSeq)
        {
            DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

            if (dtb.Rows.Count > 0)
            {
                lblEmpSeq.Text = strEmpSeq;
                lblEmpName.Text = dtb.Rows[0]["full_name"].ToString();
                lblPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
            }
        }

        protected void LoadFinProjectExpense(string strBgmProjOperSeq, string strBgmProjSeq)
        {
            double dSumAmount = 0;
            double dSumAmount1 = 0;
            double dSumAmount2 = 0;
            double dSumAmountGrp = 0;
            double dSumAmountSource = 0;
            int nOldBgmExpSeq1 = 0;
            int nOldBgmExpSeq2 = 0;
            int nOldBgmExpGrpSeq = 0;
            int nOldBgmSourceSeq = 0;
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> masterListInfo
                = poexp.GetProjectExpense(strBgmProjOperSeq, strBgmProjSeq);

            DataTable dtbSource = new DataTable();
            dtbSource.Columns.Add("bgm_source_seq", typeof(Int32));
            dtbSource.Columns.Add("bgm_source_name", typeof(String));
            dtbSource.Columns.Add("amount", typeof(Double));

            DataTable dtbExpGrp = new DataTable();
            dtbExpGrp.Columns.Add("bgm_source_seq", typeof(Int32));
            dtbExpGrp.Columns.Add("bgm_exp_grp_seq", typeof(Int32));
            dtbExpGrp.Columns.Add("bgm_exp_grp_name", typeof(String));
            dtbExpGrp.Columns.Add("amount", typeof(Double));

            DataTable dtbExp2 = new DataTable();
            dtbExp2.Columns.Add("bgm_source_seq", typeof(Int32));
            dtbExp2.Columns.Add("bgm_exp_grp_seq", typeof(Int32));
            dtbExp2.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp2.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp2.Columns.Add("amount", typeof(Double));

            DataTable dtbExp1 = new DataTable();
            dtbExp1.Columns.Add("bgm_source_seq", typeof(Int32));
            dtbExp1.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            dtbExp1.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp1.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp1.Columns.Add("amount", typeof(Double));

            DataTable dtbExp = new DataTable();
            dtbExp.Columns.Add("bgm_source_seq", typeof(Int32));
            dtbExp.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            dtbExp.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp.Columns.Add("descr", typeof(String));
            dtbExp.Columns.Add("amount", typeof(Double));

            for (int i = 0; i < masterListInfo.Count; i++)
            {
                BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense info = masterListInfo[i];
                DataRow dr = dtbExp.NewRow();
                double dAmount = (info.amount == null ? 0 : info.amount.Value);
                if (dAmount > 0)
                {
                    dr["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
                    dr["upper_bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq;
                    dr["bgm_exp_seq"] = info.m_bgm_projectexpense.bgm_exp_seq;
                    dr["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name;
                    dr["descr"] = info.bgm_proj_oper_exp_descr;
                    dr["amount"] = dAmount;
                    dtbExp.Rows.Add(dr);
                    dSumAmount += dAmount;
                    // exp1 ======================================================================================
                    if (info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq == nOldBgmExpSeq1
                            && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
                    {
                        dSumAmount1 += dAmount;
                    }
                    else
                    {
                        DataRow dr1 = dtbExp1.NewRow();
                        dr1["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
                        dr1["upper_bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq;
                        dr1["bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq;
                        dr1["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_name;

                        if (dtbExp1.Rows.Count > 0)
                        {
                            dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
                        }

                        dSumAmount1 = dAmount;
                        nOldBgmExpSeq1 = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq.Value;

                        dtbExp1.Rows.Add(dr1);
                    }
                    // exp2 ======================================================================================
                    if (info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq == nOldBgmExpSeq2
                            && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
                    {
                        dSumAmount2 += dAmount;
                    }
                    else
                    {
                        DataRow dr2 = dtbExp2.NewRow();
                        dr2["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
                        dr2["bgm_exp_grp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq;
                        dr2["bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq;
                        dr2["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_name;

                        if (dtbExp2.Rows.Count > 0)
                        {
                            dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
                        }

                        dSumAmount2 = dAmount;
                        nOldBgmExpSeq2 = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq.Value;

                        dtbExp2.Rows.Add(dr2);
                    }
                    // grp ======================================================================================
                    if (info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq == nOldBgmExpGrpSeq
                            && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
                    {
                        dSumAmountGrp += dAmount;
                    }
                    else
                    {
                        DataRow drGrp = dtbExpGrp.NewRow();
                        drGrp["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
                        drGrp["bgm_exp_grp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq;
                        drGrp["bgm_exp_grp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name;

                        if (dtbExpGrp.Rows.Count > 0)
                        {
                            dtbExpGrp.Rows[dtbExpGrp.Rows.Count - 1]["amount"] = dSumAmountGrp;
                        }

                        dSumAmountGrp = dAmount;
                        nOldBgmExpGrpSeq = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq.Value;

                        dtbExpGrp.Rows.Add(drGrp);
                    }
                    // source ======================================================================================
                    if (info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
                    {
                        dSumAmountSource += dAmount;
                    }
                    else
                    {
                        DataRow drSource = dtbSource.NewRow();
                        drSource["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
                        drSource["bgm_source_name"] = info.m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name;

                        if (dtbSource.Rows.Count > 0)
                        {
                            dtbSource.Rows[dtbSource.Rows.Count - 1]["amount"] = dSumAmountSource;
                        }

                        dSumAmountSource = dAmount;
                        nOldBgmSourceSeq = info.m_bgm_projectexpense.bgm_source_seq.Value;

                        dtbSource.Rows.Add(drSource);
                    }
                }

                if (i == masterListInfo.Count - 1 && dtbSource.Rows.Count > 0)
                {
                    dtbSource.Rows[dtbSource.Rows.Count - 1]["amount"] = dSumAmountSource;
                    dtbExpGrp.Rows[dtbExpGrp.Rows.Count - 1]["amount"] = dSumAmountGrp;
                    dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
                    dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
                }
            }

            RepeaterBgmSource.DataSource = dtbSource;
            RepeaterBgmSource.DataBind();

            for (int i = 0; i < RepeaterBgmSource.Items.Count; i++)
            {
                Repeater RepeaterBgmExpGrp = (Repeater)RepeaterBgmSource.Items[i].FindControl("RepeaterBgmExpGrp");
                Label lblBgmSourceSeq = (Label)RepeaterBgmSource.Items[i].FindControl("lblBgmSourceSeq");

                DataTable dtbExpGrpCopy = dtbExpGrp.Copy();
                dtbExpGrpCopy.Rows.Clear();
                DataRow[] drc = dtbExpGrp.Select("bgm_source_seq = " + lblBgmSourceSeq.Text);
                foreach (DataRow dr in drc)
                {
                    DataRow drCopy = dr;
                    dtbExpGrpCopy.ImportRow(drCopy);
                }

                RepeaterBgmExpGrp.DataSource = dtbExpGrpCopy;
                RepeaterBgmExpGrp.DataBind();

                for (int j = 0; j < RepeaterBgmExpGrp.Items.Count; j++)
                {
                    Repeater RepeaterBgmExp2 = (Repeater)RepeaterBgmExpGrp.Items[j].FindControl("RepeaterBgmExp2");
                    Label lblBgmExpGrpSeq = (Label)RepeaterBgmExpGrp.Items[j].FindControl("lblBgmExpGrpSeq");

                    DataTable dtbExp2Copy = dtbExp2.Copy();
                    dtbExp2Copy.Rows.Clear();
                    DataRow[] drc2 = dtbExp2.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                        + " and bgm_exp_grp_seq = " + lblBgmExpGrpSeq.Text);
                    foreach (DataRow dr in drc2)
                    {
                        DataRow drCopy = dr;
                        dtbExp2Copy.ImportRow(drCopy);
                    }

                    RepeaterBgmExp2.DataSource = dtbExp2Copy;
                    RepeaterBgmExp2.DataBind();

                    for (int k = 0; k < RepeaterBgmExp2.Items.Count; k++)
                    {
                        Repeater RepeaterBgmExp1 = (Repeater)RepeaterBgmExp2.Items[k].FindControl("RepeaterBgmExp1");
                        Label lblBgmExpSeq = (Label)RepeaterBgmExp2.Items[k].FindControl("lblBgmExpSeq");

                        DataTable dtbExp1Copy = dtbExp1.Copy();
                        dtbExp1Copy.Rows.Clear();
                        DataRow[] drc3 = dtbExp1.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                            + " and upper_bgm_exp_seq = " + lblBgmExpSeq.Text);
                        foreach (DataRow dr in drc3)
                        {
                            DataRow drCopy = dr;
                            dtbExp1Copy.ImportRow(drCopy);
                        }

                        RepeaterBgmExp1.DataSource = dtbExp1Copy;
                        RepeaterBgmExp1.DataBind();

                        for (int m = 0; m < RepeaterBgmExp1.Items.Count; m++)
                        {
                            Repeater RepeaterBgmExp = (Repeater)RepeaterBgmExp1.Items[m].FindControl("RepeaterBgmExp");
                            Label lblBgmExpSeq2 = (Label)RepeaterBgmExp1.Items[m].FindControl("lblBgmExpSeq");

                            DataTable dtbExpCopy = dtbExp.Copy();
                            dtbExpCopy.Rows.Clear();
                            DataRow[] drc4 = dtbExp.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                                + " and upper_bgm_exp_seq = " + lblBgmExpSeq2.Text);
                            foreach (DataRow dr in drc4)
                            {
                                DataRow drCopy = dr;
                                dtbExpCopy.ImportRow(drCopy);
                            }

                            RepeaterBgmExp.DataSource = dtbExpCopy;
                            RepeaterBgmExp.DataBind();
                        }
                    }
                }
            }

            lblFinSumAmount.Text = dSumAmount.ToString("#,###.00");
        }

        protected IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> GetRepeaterBgmExpData(
            string strBgmSourceSeq, string strBgmExpGrpSeq, IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> masterListInfo)
        {
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> listInfo = new List<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense>();
            string strBgmExpName = "";
            string strBgmExpSeq = "";

            for (int i = 0; i < masterListInfo.Count; i++)
            {
                BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense item = masterListInfo[i];
                Nullable<double> dBathAmount = item.amount;
                string strExpBgmSourceSeq = item.m_bgm_projectexpense.bgm_source_seq.ToString();
                string strExpBgmExpGrpSeq = item.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq.ToString();

                if (dBathAmount > 0 && strExpBgmSourceSeq == strBgmSourceSeq && strExpBgmExpGrpSeq == strBgmExpGrpSeq)
                {
                    strBgmExpSeq = item.m_bgm_projectexpense.bgm_exp_seq.ToString();
                    strBgmExpName = item.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name;

                    BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense Info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                    BGM_ProjectOperationExpense.M_BGM_ProjectExpense PjExpInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectExpense();
                    BGM_ProjectOperationExpense.M_BGM_MAS_Expense expInfo = new BGM_ProjectOperationExpense.M_BGM_MAS_Expense();

                    Info.amount = dBathAmount;

                    PjExpInfo.bgm_exp_seq = main.ConvertNullInt(strBgmExpSeq);
                    expInfo.bgm_exp_name = strBgmExpName;
                    PjExpInfo.m_bgm_mas_expense = expInfo;
                    Info.m_bgm_projectexpense = PjExpInfo;
                    Info.bgm_proj_oper_exp_descr = item.bgm_proj_oper_exp_descr;
                    listInfo.Add(Info);
                }
            }

            return listInfo;
        }

        public void cmdApprove_Click(object sender, EventArgs e)
        {
            //string strNextSeqNo = send.GetNextStepNo(lblApprovePathSeq.Text);

            //if (strNextSeqNo == "0")
            //{
            //    PanelApprove.Visible = true;
            //    PanelSendTo.Visible = false;
            //    lblMode.Text = "A";
            //}
            //else
            //{
            //    DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), "bgm_project_operation"
            //        , Convert.ToInt32(strNextSeqNo));

            //    if (dtb != null)
            //    {
            //        if (dtb.Rows.Count > 0)
            //        {
            //            lblNewApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
            //            LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
            //        }
            //    }

            PanelApprove.Visible = true;
            PanelSendTo.Visible = false;
            lblMode.Text = "A";
            //}

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdForword_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = true;
            lblMode.Text = "F";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdSendBack_Click(object sender, EventArgs e)
        {
            lblMode.Text = "B";

            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;

            lblError.Text = "";
        }

        protected void LoadEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproverEmpSeq.Text = dtb.Rows[0]["sequence"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
                lblApproverPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblApproverClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblApproverExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblApproverJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
            }
        }


        private bool directApprove = false;
        public string Approve(string remark)
        {
            cmdApprove_Click(new Object(), new EventArgs());
            txtRemark.Text = remark;
            return cmdSendClick();
        }
        public void cmdSend_Click(object sender, EventArgs e)
        {
            cmdSendClick();
        }

        public string cmdSendClick()
        {
            string strSQL = "";
            int nEmpSeqLogin = SsMng.EmpSeqI;
            BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
            ESS.MODEL.M_MessageReply replyInfo = new ESS.MODEL.M_MessageReply();
            // By Aek 2014-07-29
            // remark: in forwarding FromEmpSeq should be the previous emp_seq in message_send
            // string strFromEmpSeq = Session["EmpSeq"].ToString();
            var messageSendPrev = send.GetFull(null, null, null, null, null, null, null, lblSendSeq.Text)[0];
            string strFromEmpSeq = messageSendPrev.to_emp_seq.ToString();
            string strFromPosSeq = messageSendPrev.to_pos_seq.ToString();
               
            int nFromEmpSeq = Convert.ToInt32(strFromEmpSeq);
            int nFromPosSeq = Convert.ToInt32(strFromPosSeq);

            Nullable<int> nToEmpSeq = null;
            Nullable<int> nToPosSeq = null;
            Nullable<int> nWodEmpSeq = nEmpSeqLogin == nFromEmpSeq ? (int?)null : nEmpSeqLogin;

            bool bLeaf = true;
            string strSendSeq = lblSendSeq.Text;
            string strToEmpSeq = lblApproverEmpSeq.Text;

            if (strToEmpSeq.Length == 0 && ddlApprover.Visible)
            {
                lblError.Text = "คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง";
                return lblError.Text;
            }
            else
            {
                lblError.Text = "";
            }

            while (bLeaf)
            {
                ESS.MODEL.M_MessageSend sendInfo = send.GetInfo(strSendSeq);
                string strFromSendSeq = sendInfo.from_send_seq.ToString();

                if (string.IsNullOrEmpty(strFromSendSeq))
                {
                    bLeaf = false;
                    nToEmpSeq = sendInfo.from_emp_seq;
                    nToPosSeq = send.GetPosSeqFromEmpSeq(Convert.ToString(nToEmpSeq));
                }

                strSendSeq = strFromSendSeq;
            }

            switch (lblMode.Text)
            {
                case "A":
                    dbManager.Open();
                    dbManager.BeginTransaction();

                    try
                    {
                        operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                        operInfo.record_status = "A";
                        operInfo.updated_by = nEmpSeqLogin;
                        operInfo.updated_when = DateTime.Now;

                        dbManager.CreateParameters(2);

                        dbManager.AddParameters(0, "@bgm_proj_oper_seq", operInfo.bgm_proj_oper_seq);
                        dbManager.AddParameters(1, "@delete_record_status", SystemInfo._DeleteRecordStatus);

                        strSQL = "select coalesce(opexp.amount, 0) as amount"
                            + ", coalesce(pjre.remain_amount, 0) as remain_amount"
                            + " from bgm_project_operation op"
                            + " left join (select opexp.bgm_proj_oper_seq, exp.bgm_exp_grp_seq, pjexp.bgm_source_seq"
                                + ", sum(coalesce(amount, 0)) as amount"
                                + " from bgm_project_operation_expense opexp"
                                + " left join bgm_project_expense pjexp on opexp.bgm_proj_exp_seq = pjexp.bgm_proj_exp_seq"
                                + " left join bgm_mas_expense exp on pjexp.bgm_exp_seq = exp.bgm_exp_seq"
                                + " group by opexp.bgm_proj_oper_seq, exp.bgm_exp_grp_seq, pjexp.bgm_source_seq"
                                + ") opexp on op.bgm_proj_oper_seq = opexp.bgm_proj_oper_seq"
                            + " left join (select pjexp.bgm_proj_seq, exp.bgm_exp_grp_seq, pjexp.bgm_source_seq"
                                + ", sum(coalesce(pjre.cal_amount, 0)) as remain_amount"
                                + " from bgm_project_report pjre"
                                + " left join bgm_project_expense pjexp on pjre.bgm_proj_exp_seq = pjexp.bgm_proj_exp_seq"
                                + " left join bgm_mas_expense exp on pjexp.bgm_exp_seq = exp.bgm_exp_seq"
                                + " where pjre.record_status not like @delete_record_status"
                                + " group by pjexp.bgm_proj_seq, exp.bgm_exp_grp_seq, pjexp.bgm_source_seq"
                                + ") pjre on op.bgm_proj_seq = pjre.bgm_proj_seq"
                                + " and opexp.bgm_exp_grp_seq = pjre.bgm_exp_grp_seq"
	                            + " and opexp.bgm_source_seq = pjre.bgm_source_seq"
                            + " WHERE op.bgm_proj_oper_seq = @bgm_proj_oper_seq";
                        DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            double dBathAmount = Convert.ToDouble(dtb.Rows[i]["amount"]);
                            double dRemainAmount = Convert.ToDouble(dtb.Rows[i]["remain_amount"]);

                            if (dBathAmount > dRemainAmount)
                            {
                                string errorStr = "ไม่สามารถอนุมัติได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับอนุมัติ";
                                if (!directApprove) main.MessageAlert(Page, errorStr);
                                return errorStr;
                            }
                        }

                        dbManager.CreateParameters(4);

                        dbManager.AddParameters(0, "@bgm_proj_oper_seq", operInfo.bgm_proj_oper_seq);
                        dbManager.AddParameters(1, "@record_status", operInfo.record_status);
                        dbManager.AddParameters(2, "@updated_by", operInfo.updated_by);
                        dbManager.AddParameters(3, "@updated_when", operInfo.updated_when);

                        strSQL = "UPDATE bgm_project_operation"
                            + " SET record_status = @record_status"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                            + " WHERE bgm_proj_oper_seq = @bgm_proj_oper_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> expListInfo = poexp.GetFull(lblBgmProjOperSeq.Text, null, null);
                        for (int i = 0; i < expListInfo.Count; i++)
                        {
                            BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense expInfo = expListInfo[i];
                            BGM_ProjectOperationReport.M_BGM_ProjectOperationReport reportInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                            reportInfo.bgm_proj_oper_exp_seq = expInfo.bgm_proj_oper_exp_seq;
                            reportInfo.used_amount = expInfo.amount;
                            reportInfo.cal_amount = expInfo.amount;
                            reportInfo.rpt_type = 1; //เหมือนจัดสรร
                            reportInfo.created_by = nEmpSeqLogin;
                            reportInfo.created_when = DateTime.Now;
                            //poreport.Insert(reportInfo);

                            dbManager.CreateParameters(15);

                            dbManager.AddParameters(0, "@bgm_proj_oper_rpt_seq", reportInfo.bgm_proj_oper_rpt_seq);
                            dbManager.AddParameters(1, "@descr", reportInfo.descr);
                            dbManager.AddParameters(2, "@bgm_proj_oper_exp_seq", reportInfo.bgm_proj_oper_exp_seq);
                            dbManager.AddParameters(3, "@bgm_trans_from_seq", "");
                            dbManager.AddParameters(4, "@bgm_trans_to_seq", "");
                            dbManager.AddParameters(5, "@money_req_dtls_seq", reportInfo.money_req_dtls_seq);
                            dbManager.AddParameters(6, "@return_dtls_seq", reportInfo.return_dtls_seq);
                            dbManager.AddParameters(7, "@petition_dtls_seq", reportInfo.petition_dtls_seq);
                            dbManager.AddParameters(8, "@pay_seq", reportInfo.pay_seq);

                            dbManager.AddParameters(9, "@used_amount", reportInfo.used_amount);
                            dbManager.AddParameters(10, "@cal_amount", reportInfo.cal_amount);
                            dbManager.AddParameters(11, "@rpt_type", reportInfo.rpt_type);

                            dbManager.AddParameters(12, "@record_status", SystemInfo._ActiveRecordStatus);
                            dbManager.AddParameters(13, "@created_by", reportInfo.created_by);
                            dbManager.AddParameters(14, "@created_when", reportInfo.created_when);

                            strSQL = "select count(*) as row_count"
                                + " from bgm_project_operation_report"
                                + " where bgm_proj_oper_exp_seq = @bgm_proj_oper_exp_seq"
                                + " and record_status <> 'D'";
                            var exists = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                            if (exists.Rows.Count > 0 && (main.ConvertNullInt(exists.Rows[0][0]) ?? 0) > 0)
                            {
                                dbManager.RollBackTransaction();
                                main.MessageAlert(Page, "มีการทำรายการซ้ำ");
                                return "";
                            }

                            strSQL = "INSERT INTO bgm_project_operation_report"
                                + "(descr, bgm_proj_oper_exp_seq"//, bgm_trans_from_seq, bgm_trans_to_seq"
                                    + ", money_req_dtls_seq, return_dtls_seq, petition_dtls_seq, pay_seq"
                                    + ", used_amount, cal_amount, rpt_type"
                                    + ", record_status, created_by, created_when)"
                                + " VALUES (@descr, @bgm_proj_oper_exp_seq"//, @bgm_trans_from_seq, @bgm_trans_to_seq"
                                    + ", @money_req_dtls_seq, @return_dtls_seq, @petition_dtls_seq, @pay_seq"
                                    + ", @used_amount, @cal_amount, @rpt_type"
                                    + ", @record_status, @created_by, @created_when)";

                            dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                            BGM_ProjectReport.M_BGM_ProjectReport pjreportInfo = new BGM_ProjectReport.M_BGM_ProjectReport();
                            pjreportInfo.bgm_proj_exp_seq = expInfo.bgm_proj_exp_seq;
                            pjreportInfo.used_amount = expInfo.amount;
                            pjreportInfo.cal_amount = -expInfo.amount;
                            pjreportInfo.rpt_type = 4; //เหมือนกันเงิน
                            pjreportInfo.created_by = nEmpSeqLogin;
                            pjreportInfo.created_when = DateTime.Now;
                            pjreportInfo.bgm_proj_oper_exp_seq = expInfo.bgm_proj_oper_exp_seq;
                            //pjreport.Insert(pjreportInfo);

                            dbManager.CreateParameters(13);

                            dbManager.AddParameters(0, "@bgm_proj_rpt_seq", pjreportInfo.bgm_proj_rpt_seq);
                            dbManager.AddParameters(1, "@descr", pjreportInfo.descr);
                            dbManager.AddParameters(2, "@bgm_proj_exp_seq", pjreportInfo.bgm_proj_exp_seq);
                            dbManager.AddParameters(3, "@bgm_rec_seq", "");
                            dbManager.AddParameters(4, "@bgm_trans_from_seq", "");
                            dbManager.AddParameters(5, "@bgm_trans_to_seq", "");
                            dbManager.AddParameters(6, "@bgm_proj_oper_exp_seq", pjreportInfo.bgm_proj_oper_exp_seq);
                            dbManager.AddParameters(7, "@used_amount", pjreportInfo.used_amount);
                            dbManager.AddParameters(8, "@cal_amount", pjreportInfo.cal_amount);
                            dbManager.AddParameters(9, "@rpt_type", pjreportInfo.rpt_type);

                            dbManager.AddParameters(10, "@record_status", SystemInfo._ActiveRecordStatus);
                            dbManager.AddParameters(11, "@created_by", pjreportInfo.created_by);
                            dbManager.AddParameters(12, "@created_when", pjreportInfo.created_when);

                            strSQL = "INSERT INTO bgm_project_report"
                                + "(descr, bgm_proj_exp_seq"
                                    + ", bgm_proj_oper_exp_seq, used_amount, cal_amount, rpt_type"
                                    + ", record_status, created_by, created_when)"
                                + " VALUES (@descr, @bgm_proj_exp_seq"
                                    + ", @bgm_proj_oper_exp_seq, @used_amount, @cal_amount, @rpt_type"
                                    + ", @record_status, @created_by, @created_when)";

                            dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                        }

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(info.send_seq);
                        replyInfo.reply_type = "1";
                        replyInfo.reply_text = "อนุมัติให้ดำเนินโครงการได้ : " + lblFinBgmProjOperName.Text;
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        replyInfo.remarks = txtRemark.Text;
                        //reply.Insert(replyInfo);

                        dbManager.CreateParameters(16);

                        dbManager.AddParameters(0, "@reply_seq", replyInfo.reply_seq);
                        dbManager.AddParameters(1, "@reply_date", replyInfo.reply_date == null ? DBNull.Value : (object)replyInfo.reply_date);
                        dbManager.AddParameters(2, "@ref_no", replyInfo.ref_no == null ? DBNull.Value : (object)replyInfo.ref_no);
                        dbManager.AddParameters(3, "@reply_text", replyInfo.reply_text == null ? DBNull.Value : (object)replyInfo.reply_text);
                        dbManager.AddParameters(4, "@reply_type", replyInfo.reply_type == null ? DBNull.Value : (object)replyInfo.reply_type);
                        dbManager.AddParameters(5, "@from_emp_seq", replyInfo.from_emp_seq == null ? DBNull.Value : (object)replyInfo.from_emp_seq);
                        dbManager.AddParameters(6, "@to_emp_seq", replyInfo.to_emp_seq == null ? DBNull.Value : (object)replyInfo.to_emp_seq);
                        dbManager.AddParameters(7, "@from_send_seq", replyInfo.from_send_seq == null ? DBNull.Value : (object)replyInfo.from_send_seq);
                        dbManager.AddParameters(8, "@remarks", replyInfo.remarks == null ? DBNull.Value : (object)replyInfo.remarks);
                        dbManager.AddParameters(9, "@message_status", replyInfo.message_status == null ? DBNull.Value : (object)replyInfo.message_status);

                        dbManager.AddParameters(10, "@record_status", SystemInfo._ActiveRecordStatus);
                        dbManager.AddParameters(11, "@created_by", replyInfo.created_by);
                        dbManager.AddParameters(12, "@created_when", replyInfo.created_when);

                        dbManager.AddParameters(13, "@from_pos_seq", replyInfo.from_pos_seq);
                        dbManager.AddParameters(14, "@to_pos_seq", replyInfo.to_pos_seq);
                        dbManager.AddParameters(15, "@wod_emp_seq", replyInfo.wod_emp_seq);

                        strSQL = "INSERT INTO message_reply"
                            + "(reply_date, ref_no, reply_text, reply_type"
                            + ", from_emp_seq, to_emp_seq, from_send_seq, remarks, message_status"
                            + ", from_pos_seq, to_pos_seq, wod_emp_seq"
                            + ", record_status, created_by, created_when)"
                            + " VALUES(@reply_date"
                                + ", @ref_no"
                                + ", @reply_text"
                                + ", @reply_type"
                                + ", @from_emp_seq"
                                + ", @to_emp_seq"
                                + ", @from_send_seq"
                                + ", @remarks"
                                + ", @message_status"
                                + ", @from_pos_seq"
                                + ", @to_pos_seq"
                                + ", @wod_emp_seq"

                                + ", @record_status"
                                + ", @created_by"
                                + ", @created_when);"
                            + " SELECT scope_identity();";
                        var strSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        //send.UpdateMessageStatus(info);

                        dbManager.CreateParameters(5);

                        dbManager.AddParameters(0, "@send_seq", info.send_seq);
                        dbManager.AddParameters(1, "@message_status", info.message_status);
                        dbManager.AddParameters(2, "@updated_by", info.updated_by);
                        dbManager.AddParameters(3, "@updated_when", info.updated_when);
                        dbManager.AddParameters(4, "@wod_emp_seq", info.wod_emp_seq);

                        strSQL = "UPDATE message_send"
                            + " SET message_status = @message_status"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                                 + ", wod_emp_seq = @wod_emp_seq"
                            + " WHERE send_seq = @send_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        dbManager.CommitTransaction();
                    }
                    catch
                    {
                        dbManager.RollBackTransaction();
                        string errorStr = "พบข้อผิดพลาดระหว่างการอนุมัติ";
                        if (!directApprove) main.MessageAlert(Page, errorStr);
                        return errorStr;
                    }
                    finally
                    {
                        dbManager.Dispose();
                    }
                    break;
                case "F":
                    operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                    operInfo.record_status = "P";
                    operInfo.updated_by = nEmpSeqLogin;
                    operInfo.updated_when = DateTime.Now;
                    if (!oper.ChangeStatus(operInfo))
                    {
                        string errorStr = "ไม่สามารถส่งต่อได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับจัดสรร";
                        if (!directApprove) main.MessageAlert(Page, errorStr);
                        return errorStr;
                    }

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(lblBgmProjOperSeq.Text);
                    info.ref_type = "bgm_project_operation";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    info.send_text = "ส่งคำขออนุมัติดำเนินงาน : " + lblFinBgmProjOperName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;
                    info.to_emp_seq = main.ConvertNullInt(strToEmpSeq);
                    info.to_pos_seq = send.GetPosSeqFromEmpSeq(strToEmpSeq);
                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;
                    send.Insert(info);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
                case "B":
                    operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                    operInfo.record_status = "R";
                    operInfo.updated_by = nFromEmpSeq;
                    operInfo.updated_when = DateTime.Now;
                    oper.ChangeStatus(operInfo);

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(lblBgmProjOperSeq.Text);
                    info.ref_type = "return";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    info.send_text = "ส่งกลับเพื่อแก้ไข : " + lblFinBgmProjOperName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;
                    info.to_emp_seq = nToEmpSeq;
                    info.to_pos_seq = nToPosSeq;
                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = null;//main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;
                    send.Insert(info);

                    replyInfo.reply_date = DateTime.Today;
                    replyInfo.ref_no = send.GetRefNoOfSendSeq(info.send_seq);
                    replyInfo.reply_type = "0";
                    replyInfo.reply_text = "ส่งกลับมาเพื่อแก้ไข : " + lblFinBgmProjOperName.Text;
                    replyInfo.from_emp_seq = nFromEmpSeq;
                    replyInfo.from_pos_seq = nFromPosSeq;
                    replyInfo.to_emp_seq = nToEmpSeq;
                    replyInfo.to_pos_seq = nToPosSeq;
                    replyInfo.wod_emp_seq = nWodEmpSeq;
                    replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                    replyInfo.remarks = txtRemark.Text;
                    replyInfo.message_status = "0";
                    replyInfo.created_by = nEmpSeqLogin;
                    replyInfo.created_when = DateTime.Now;
                    reply.Insert(replyInfo);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
            }

            ((TaskListsPopUp) Page).cmdViewRequest_Click(null, null);
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            // button
            PanelOption.Visible = true;
            PanelSend.Visible = false;
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadEmpInfo(ddlApprover.SelectedValue);
        }
    }
}